﻿using JNPF.Basics.Models;
using JNPF.Utils.Quartz;
using Quartz;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    public class MyJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(async () =>
            {
                var jobDetail = context.JobDetail;
                var jobKey = jobDetail.Key;
                var dataMap = context.MergedJobDataMap;
                var tenantId = jobKey.Group.Split("-")[0];
                var entity = dataMap.WrappedMap["data"] != null ? (TimeTaskEntity)dataMap.WrappedMap["data"] : null;
                var model = dataMap.WrappedMap["content"] != null ? (ContentModel)dataMap.WrappedMap["content"] : null;
                var type = dataMap.GetIntValue("type");
                if (type == 1)
                {
                    if (entity != null)
                    {
                        if (entity.ExecuteType == "2")
                        {
                            CronUtil.Instance.Storage(model, entity, tenantId);
                        }
                        else if (entity.ExecuteType == "1")
                        {
                            CronUtil.Instance.Connector(model, entity, tenantId);
                        }
                    }
                }
                else if (type == 2)
                {
                    if (model.frequency == "1")
                    {
                        await QuartzHelper.Stop(jobKey);
                        if (entity.ExecuteType == "2")
                        {
                            CronUtil.Instance.Storage(model, entity, tenantId);
                        }
                        else if (entity.ExecuteType == "1")
                        {
                            CronUtil.Instance.Connector(model, entity, tenantId);
                        }
                    }
                    else
                    {
                        dataMap.Add("type", 1);
                        if (model.frequency != "3")
                        {
                            await QuartzHelper.Stop(jobKey);
                            CronUtil.Instance.StartJobAsync(entity, model, tenantId);
                        }
                        else if (model.frequency == "3")
                        {
                            string[] cycle = entity.ExecuteCycleJson.Split(";");
                            for (int i = 0; i < cycle.Length; i++)
                            {
                                string cron = cycle[i];
                                await QuartzHelper.Stop(jobKey);
                                CronUtil.Instance.StartJobAsync(entity, model, tenantId);
                            }
                        }
                    }
                }
                else if (type == 3)
                {
                    await QuartzHelper.Stop(jobKey);
                }
            });
        }
    }
}
